package com.example.peibei.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.dingtao.common.bean.User;
import com.dingtao.common.core.DataCall;
import com.dingtao.common.core.WDActivity;
import com.dingtao.common.core.exception.ApiException;
import com.dingtao.common.util.SPUtils;
import com.dingtao.common.util.UIUtils;
import com.example.peibei.R;
import com.example.peibei.base.SpConstant;
import com.example.peibei.bean.SpUserInfoCall;
import com.example.peibei.service.presenter.ChcekTextPresenter;
import com.example.peibei.service.presenter.EditUserInfoPresenter;
import com.example.peibei.service.presenter.UploadImagePresenter;
import com.example.peibei.service.presenter.UserInfoPresenter;
import com.example.peibei.ui.weight.AddressPickTask;
import com.example.peibei.ui.weight.GlideEngine;
import com.example.peibei.ui.weight.NickNameDialog;
import com.linxiao.framework.common.ScreenUtil;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.yxp.permission.util.lib.PermissionUtil;
import com.yxp.permission.util.lib.callback.PermissionResultCallBack;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.addapp.pickers.entity.City;
import cn.addapp.pickers.entity.County;
import cn.addapp.pickers.entity.Province;
import cn.addapp.pickers.picker.DatePicker;
import cn.addapp.pickers.picker.NumberPicker;
import cn.addapp.pickers.picker.SinglePicker;
import cn.jpush.android.api.JPushInterface;

public class EditInfoActivity extends WDActivity {
    @BindView(R.id.et_nickname)
    TextView et_nickname;
    @BindView(R.id.iv_head)
    ImageView iv_head;
    @BindView(R.id.tv_sg)
    TextView tv_sg;
    @BindView(R.id.tv_age)
    TextView tv_age;
    @BindView(R.id.tv_address)
    TextView tv_address;
    @BindView(R.id.tv_work)
    TextView tv_work;
    @BindView(R.id.tv_gender)
    TextView tv_gender;
    @BindView(R.id.et_order)
    EditText et_order;
    @BindView(R.id.rl_img)
    RelativeLayout rl_img;

    private UserInfoPresenter userInfoPresenter;
    private SPUtils spUtils;
    private String token;
    private UploadImagePresenter uploadImagePresenter;
    private String nickName;
    private String ImagePath;
    private String birthday = "";
    private String area;
    private String job;
    private String sign;
    private int height;
    private long memberId;
    private EditUserInfoPresenter editUserInfoPresenter;
    private ChcekTextPresenter chcekTextPresenter;
    private String content;
    private int gender;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_editinfo;
    }

    @Override
    protected void initView() {
        spUtils = new SPUtils(EditInfoActivity.this, SpConstant.USER_TOKEN);
        token = spUtils.getString(SpConstant.USER_TOKEN);
        uploadImagePresenter = new UploadImagePresenter(new UploadCall());
        editUserInfoPresenter = new EditUserInfoPresenter(new EditUserInfoCall());
        userInfoPresenter = new UserInfoPresenter(new UserInfoCall());
        chcekTextPresenter = new ChcekTextPresenter(new CheckTextCall());
        userInfoPresenter.reqeust("Bearer " + token);
        et_nickname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String firstName = spUtils.getString(SpConstant.FIRST_NAME, "");
                String nName = spUtils.getString(SpConstant.NICK_NAME, "");
                if (TextUtils.equals(firstName,nName)){
                    NickNameDialog dialog = new NickNameDialog(EditInfoActivity.this, et_nickname.getText().toString().trim());
                    dialog.setOnClickBottomListener(new NickNameDialog.OnClickBottomListener() {
                        @Override
                        public void onContent(String nickname) {
                            et_nickname.setText(nickname);
                            nickName = et_nickname.getText().toString();
                        }
                    });
                    dialog.show();
                }else {
                    intent(MemberActivity.class);
                }

            }
        });
    }

    @OnClick(R.id.rl_img)
    public void chooseHead() {
        showChooseImageDialog();
    }

    @OnClick(R.id.rl_choose_age)
    public void chooseAge() {
        showChooseBirthday();
    }

    @OnClick(R.id.rl_height)
    public void chooseHeight() {
        showChooseHeight();
    }

    @OnClick(R.id.rl_area)
    public void chooseArea() {
        showChooseArea();
    }

    @OnClick(R.id.rl_gender)
    public void chooseGender() {
        showChooseWeek();
    }

    private void showChooseWeek() {
        ArrayList<String> list = new ArrayList<>();
        list.add("男生");
        list.add("女生");
        SinglePicker<String> picker = new SinglePicker<>(this, list);
        Window window = picker.getWindow();
        if (window != null) {
//            window.setGravity(Gravity.BOTTOM);
            ////解决宽度问题
            window.setGravity(Gravity.BOTTOM);
            WindowManager.LayoutParams params = window.getAttributes();
            params.width = ViewGroup.LayoutParams.MATCH_PARENT;
            params.height = WindowManager.LayoutParams.WRAP_CONTENT;
            window.setAttributes(params);
            window.setBackgroundDrawableResource(R.drawable.shape_white_bg);
        }
        picker.setCanLoop(false);//不禁用循环
        picker.setLineVisible(true);
        picker.setTextSize(16);
        picker.setSelectedIndex(0);
        picker.setItemWidth(200);
        picker.setOuterLabelEnable(true);
        picker.setGravity(Gravity.BOTTOM);
        picker.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        picker.setLineColor(ContextCompat.getColor(this, R.color.color_EEEEEE));
        picker.setSelectedTextColor(ContextCompat.getColor(this, R.color.text_dark_gray));//前四位值是透明度
        picker.setUnSelectedTextColor(ContextCompat.getColor(this, R.color.color_9C9DA1));
        picker.setOnSingleWheelListener((index, item) -> {

        });
        picker.setOnItemPickListener((index, item) -> {
            tv_gender.setText(item);
            gender = index == 0 ? 1 : 0;
        });
        picker.show();
    }

    @OnClick(R.id.rl_choose_word)
    public void chooseWork() {
        Bundle bundle = new Bundle();
        bundle.putString("job", tv_work.getText().toString());
        Intent intent = new Intent(EditInfoActivity.this, ChooseWordActivity.class);
        startActivityForResult(intent, 1, bundle);
    }

    class CheckTextCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {

            spUtils.putString(SpConstant.NICK_NAME, content);
            //保存信息
            sign = et_order.getText().toString().trim();
            editUserInfoPresenter.reqeust("Bearer " + token, memberId, area, birthday, gender, height, ImagePath, job, nickName, sign);
        }

        @Override
        public void fail(ApiException e, Object... args) {
            UIUtils.showToastSafe("您的输入的昵称含有不合法的内容，请遵守用户协议相关内容");
        }

    }

    @OnClick(R.id.bt_save)
    public void save() {
        content = et_nickname.getText().toString().trim();
        if (content.equals("")) {
            UIUtils.showToastSafe("内容不能为空");
            return;
        }
        chcekTextPresenter.reqeust("Bearer " + token, content);
    }

    private void showChooseArea() {
        AddressPickTask task = new AddressPickTask(this);
        task.setHideCounty(true);
        task.setCallback(new AddressPickTask.Callback() {
            @Override
            public void onAddressInitFailed() {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onAddressPicked(Province province, City city, County county) {
                area = province.getAreaName() + " " + city.getAreaName();
                tv_address.setText(province.getAreaName() + city.getAreaName());
            }
        });
        task.execute("四川", "成都");
    }

    private void showChooseHeight() {
        NumberPicker picker = new NumberPicker(this);
        Window window = picker.getWindow();
        if (window != null) {
//            window.setGravity(Gravity.BOTTOM);
            ////解决宽度问题
            window.setGravity(Gravity.BOTTOM);
            WindowManager.LayoutParams params = window.getAttributes();
            params.width = ViewGroup.LayoutParams.MATCH_PARENT;
            params.height = WindowManager.LayoutParams.WRAP_CONTENT;
            window.setAttributes(params);
            window.setBackgroundDrawableResource(R.drawable.shape_white_bg);
        }

        picker.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        picker.setHeight(ScreenUtil.getRealScreenWidth());
        picker.setCanLoop(false);
        picker.setLineVisible(false);
        picker.setOffset(2);//偏移量
        picker.setLineColor(ContextCompat.getColor(this, R.color.color_EEEEEE));
        picker.setSelectedTextColor(ContextCompat.getColor(this, R.color.text_dark_gray));//前四位值是透明度
        picker.setUnSelectedTextColor(ContextCompat.getColor(this, R.color.color_9C9DA1));
        picker.setGravity(Gravity.BOTTOM);
        picker.setRange(145, 200, 1);//数字范围
        picker.setSelectedItem(172);
        picker.setLabel("厘米");
        picker.setOnNumberPickListener(new NumberPicker.OnNumberPickListener() {
            @Override
            public void onNumberPicked(int index, Number item) {
                tv_sg.setText(item.intValue() + "");
                height = item.intValue();
//                ToastUtils.showShort("index=" + index + ", item=" + item.intValue());
            }
        });
        picker.show();
    }

    private void showChooseBirthday() {
        final DatePicker picker = new DatePicker(this);
        Window window = picker.getWindow();
        if (window != null) {
//            window.setGravity(Gravity.BOTTOM);
            ////解决宽度问题
            window.setGravity(Gravity.BOTTOM);
            WindowManager.LayoutParams params = window.getAttributes();
            params.width = ViewGroup.LayoutParams.MATCH_PARENT;
            params.height = WindowManager.LayoutParams.WRAP_CONTENT;
            window.setAttributes(params);
        }
        picker.setTopPadding(15);
        picker.setRangeStart(1960, 8, 29);
        picker.setRangeEnd(2021, 1, 11);
        picker.setSelectedItem(1991, 10, 14);
        picker.setWeightEnable(true);
        picker.setLineColor(ContextCompat.getColor(this, R.color.color_EEEEEE));
        picker.setSelectedTextColor(ContextCompat.getColor(this, R.color.text_dark_gray));//前四位值是透明度
        picker.setUnSelectedTextColor(ContextCompat.getColor(this, R.color.color_9C9DA1));
        picker.setGravity(Gravity.BOTTOM);
        picker.setHeight(ScreenUtil.getRealScreenWidth());
        picker.getWindow().setBackgroundDrawableResource(R.drawable.shape_white_bg);
        picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
            @Override
            public void onDatePicked(String year, String month, String day) {
                tv_age.setText(year + "-" + month + "-" + day);
                birthday = year + "-" + month + "-" + day;
            }
        });
        picker.setOnWheelListener(new DatePicker.OnWheelListener() {
            @Override
            public void onYearWheeled(int index, String year) {
                picker.setTitleText(year + "-" + picker.getSelectedMonth() + "-" + picker.getSelectedDay());
            }

            @Override
            public void onMonthWheeled(int index, String month) {
                picker.setTitleText(picker.getSelectedYear() + "-" + month + "-" + picker.getSelectedDay());
            }

            @Override
            public void onDayWheeled(int index, String day) {
                picker.setTitleText(picker.getSelectedYear() + "-" + picker.getSelectedMonth() + "-" + day);
            }
        });
        picker.show();
    }

    private void showChooseImageDialog() {
        getPermission();
    }

    private static String[] PERMISSIONS = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA
    };

    private void getPermission() {
        PermissionUtil.getInstance().request(this, PERMISSIONS,
                new PermissionResultCallBack() {
                    @Override
                    public void onPermissionGranted() {
                        showAlbum();
                    }

                    @Override
                    public void onPermissionGranted(String... strings) {
                        // 当所有权限的申请被用户同意之后,该方法会被调用
                        //get_NovelUrl(id);
                    }

                    @Override
                    public void onPermissionDenied(String... permissions) {
                        UIUtils.showToastSafe("部分权限被禁止需要手动开启");
                        // 当权限申请中的某一个或多个权限,被用户曾经否定了,并确认了不再提醒时,也就是权限的申请窗口不能再弹出时,该方法将会被调用
                        getPermission();
                    }

                    @Override
                    public void onRationalShow(String... permissions) {
                        UIUtils.showToastSafe("部分权限被禁止需要手动开启");
                        // 当权限申请中的某一个或多个权限,被用户否定了,但没有确认不再提醒时,也就是权限窗口申请时,但被否定了之后,该方法将会被调用.
                        getPermission();

                    }

                });
    }

    private void showAlbum() {
        PictureSelector.create(EditInfoActivity.this)
                .openGallery(PictureMimeType.ofImage())
                .isAndroidQTransform(false)
                .loadImageEngine(GlideEngine.createGlideEngine())
                .maxSelectNum(1)
                .minSelectNum(1)
                .compress(true)
                .selectionMode(PictureConfig.SINGLE)
                .forResult(PictureConfig.CHOOSE_REQUEST);

    }

    private Bitmap compressQuality(Bitmap bitmap) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 30, bos);
        byte[] bytes = bos.toByteArray();
        Log.e("bitmapsize", String.valueOf(bytes.length));
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /*结果回调*/
        if (requestCode == PictureConfig.CHOOSE_REQUEST) {
            if (data != null) {
                List<LocalMedia> localMedia = PictureSelector.obtainMultipleResult(data);
//                Bitmap bitmap = BitmapFactory.decodeFile(localMedia.get(0).getCompressPath());
//                iv_head.setImageBitmap(compressQuality(bitmap));
                Glide.with(EditInfoActivity.this).load(localMedia.get(0).getCompressPath()).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(iv_head);
                uploadImagePresenter.reqeust(localMedia.get(0).getCompressPath(), "Bearer " + token);
            }
        } else if (requestCode == 1 && resultCode == 3) {
            String result = data.getStringExtra("job");
            job = result;
            tv_work.setText(result);
        }
    }

    class UploadCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
            Log.i("answer", "图片上传成功：" + data);
            ImagePath = data;
//            Glide.with(EditInfoActivity.this).load(data).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(iv_head);
        }

        @Override
        public void fail(ApiException e, Object... args) {
        }
    }

    class EditUserInfoCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
            UIUtils.showToastSafe("保存成功");
            finish();
        }

        @Override
        public void fail(ApiException e, Object... args) {
        }
    }

    class UserInfoCall extends SpUserInfoCall {

        @Override
        public void success(User data, Object... args) {
            super.success(data,args);
            gender = data.getGender();
            memberId = data.getId();
            et_nickname.setText(data.getNickName());
            nickName = data.getNickName();
            if (!TextUtils.isEmpty(data.getImgUrl())) {
                Glide.with(EditInfoActivity.this).load(data.getImgUrl()).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(iv_head);
                ImagePath = data.getImgUrl();
            }
            if (data.getHeight() != 0) {
                tv_sg.setText(data.getHeight() + "");
                height = data.getHeight();
            }
            if (!TextUtils.isEmpty(data.getBirthday())) {
                tv_age.setText(data.getBirthday());
                birthday = data.getBirthday();
            }
            if (!TextUtils.isEmpty(data.getArea())) {
                tv_address.setText(data.getArea());
                area = data.getArea();
            }
            if (!TextUtils.isEmpty(data.getJob())) {
                tv_work.setText(data.getJob());
                job = data.getJob();
            }
            if (!TextUtils.isEmpty(data.getSign())) {
                et_order.setText(data.getSign());
                sign = data.getSign();
            }
            tv_gender.setText(data.getGender() == 0 ? "女生" : "男生");
        }

        @Override
        public void fail(ApiException e, Object... args) {

        }

    }

    @OnClick(R.id.iv_back)
    public void onBack() {
        finish();
    }

    @Override
    protected void destoryData() {
//        FileUtils.deleteAllCacheImage(this);
    }
}
